import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'

import Main from '@/views/Main/Main.vue'

import Home from '@/views/menus/Home/Home.vue'
import Userinfo from '@/views/menus/User/Userinfo.vue'

import UserAvatar from '@/views/menus/User/UserAvatar.vue'

import UserPwd from '@/views/menus/User/UserPwd.vue'

import ArtCate from '@/views/menus/Article/ArtCate.vue'

import ArtList from '@/views/menus/Article/ArtList.vue'

Vue.use(VueRouter)

// 覆盖vue-router的原生push
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  // 后台主页面的路由规则
  {
    path: '/',
    component: Main,
    redirect: '/home',
    children: [{ path: 'home', component: Home }, { path: '/user-info', component: Userinfo }, { path: 'user-avatar', component: UserAvatar }, { path: 'user-pwd', component: UserPwd }, { path: 'art-cate', component: ArtCate }, { path: 'art-list', component: ArtList }
    ]
  },
  { path: '/reg', component: Reg },
  // 登陆页面的路由规则
  { path: '/login', component: Login }
]

// 创建路由对象
const router = new VueRouter({
  routes
})

// 生命全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 1.登录和注册页面，不需要访问权限，直接放行
  // 2.除此之外，都需要访问权限，
  // 3.从vuex中获取token的值，判断是否有token
  // 3.1如果有token，认为用户已经登陆了，放行
  // 3.2如果没有token，认为没有登陆，强制跳转到登录页
  if (to.path === '/login' || to.path === '/reg') {
    // 直接放行
    next()
  } else {
    // 判断是否有token值
    if (store.state.token) {
      // 有值，放行
      next()
    } else {
      // 没有值，强制跳转登录页
      next('/login')
    }
  }
})

export default router
